package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {
    
    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
    
    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    
    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    
    
    @Value("${wechat.appid}")
    private String appid;
    
    @Value("${wechat.secret}")
    private String secret;
    
    
    /**
     * 获取openid
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenid(String code) {
        
        //构建参数
        Map<String, Object> paramMap = getParams();
        paramMap.put("js_code", code);
        
        //发请求
        String result = HttpUtil.get(REQUEST_URL, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断接口是否调通
        if (ObjectUtil.isNotEmpty(jsonObject.get("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        
        String openid = jsonObject.getStr("openid");
        return openid;
    }
    
    /**
     * 获取手机号
     *
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhone(String phoneCode) {
        
        String url = PHONE_REQUEST_URL + getToken();
        //参数
        Map<String, Object> params = new HashMap<>();
        params.put("code", phoneCode);
        //发起请求
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(params));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断接口是否调通
        if (jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        
        //获取结果
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }
    
    private String getToken() {
        Map<String, Object> params = getParams();
        String result = HttpUtil.get(TOKEN_URL, params);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断接口是否调通
        if (ObjectUtil.isNotEmpty(jsonObject.get("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }
    
    private Map<String, Object> getParams() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appid);
        paramMap.put("secret", secret);
        return paramMap;
    }
}
